package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.dto.resp.R;
import com.itheima.reggie.util.BaseContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.info("过滤器");
        HttpServletRequest req = (HttpServletRequest) request;

        HttpServletResponse resp = (HttpServletResponse) response;
        //1.获取本次请求的路径
        String url = req.getRequestURI();
        log.info("拦截到的请求:{}", url);
        //2.定义不需要处理的请求
        String[] urls = {"/employee/login", "/employee/logout", "/backend", "/front","/common","/user/login","/user/sendMsg"};
        //3.遍历数组,获取每一个需要放行的路径
        for (String u : urls) {
            //判断当前访问的路径字符串是否包含需要放行的资源路径
            if (url.contains(u)) {//包含了路径,可以放行
                log.info("url:{}", url);
                chain.doFilter(req, resp);
                return;
            }
        }
        //放行之后,判断是否需要登录
        //如果已登录.直接放行
        if (req.getSession().getAttribute("employee") != null) {
            log.info("用户已登录,id为:{}", req.getSession().getAttribute("employee"));
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            chain.doFilter(req, resp);
            return;
        }
        if (req.getSession().getAttribute("user") != null) {
            log.info("用户已登录,id为:{}", req.getSession().getAttribute("user"));
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            chain.doFilter(req, resp);
            return;
        }
        log.info("用户未登录");
            //未登录状态,返回未登录结果
            resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }
}
